#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <thread>
#include <chrono>
#include <cmath>
#include "hidbox/hid_device_manager.h"
#include "hidbox/mouse_descriptor_builder.h"
#include "base/logging.h"

using namespace hidbox;

static bool running = true;

void signal_handler(int signal) {
    if (signal == SIGINT || signal == SIGTERM) {
        LOG_INFO("Received signal {}, shutting down...", signal);
        running = false;
    }
}

int main(int argc, char** argv) {
    if (geteuid() != 0) {
        std::cerr << "Error: This program must be run as root." << std::endl;
        return 1;
    }

    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    try {
        LOG_INFO("HID_BOX Custom Mouse Example");
        LOG_INFO("================================");

        // 创建 HID 设备管理器
        HIDDeviceManager manager;

        // 配置自定义鼠标设备
        HIDDeviceConfig config;
        config.auto_detect = false;  // 使用自定义配置
        config.custom.vendor_id = 0x1234;
        config.custom.product_id = 0x5678;
        config.custom.manufacturer = "HIDBox";
        config.custom.product = "Custom Virtual Mouse";
        config.custom.serial = "12345678";

        // 生成 5 键带滚轮的鼠标描述符
        config.custom.report_descriptor = MouseDescriptorBuilder::BuildMouseWithWheel();

        config.gadget_name = "hidbox_custom";
        config.hid_number = 0;

        LOG_INFO("Configuring custom HID mouse...");
        manager.Configure(config);

        LOG_INFO("Simulating mouse movements in a circle pattern...");
        LOG_INFO("Press Ctrl+C to stop.");

        // 模拟鼠标画圆形移动
        float angle = 0.0f;
        const float radius = 50.0f;
        const float step = 0.1f;

        while (running) {
            MouseReport report{};
            report.buttons = 0;
            report.x = static_cast<s8>(radius * std::cos(angle) * step);
            report.y = static_cast<s8>(radius * std::sin(angle) * step);
            report.wheel = 0;

            manager.WriteToOutput(&report, sizeof(report));

            angle += 0.05f;
            if (angle > 2.0f * M_PI) {
                angle = 0.0f;
            }

            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }

        LOG_INFO("Shutdown complete");
    } catch (const std::exception& e) {
        LOG_ERROR("Fatal error: {}", e.what());
        return 1;
    }

    return 0;
}
